package com.lyy.mycart;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class CartActivity extends Activity {
	String url = "http://" + MyApplication.IP + ":8080/StoreDetail/storeSevlet";
	Cartbean cartbean;
	TextView cartTotalPrice, delete_goods, checkOut;// 价格，删除商品，结算
	CheckBox cart_all_check;
	ListView cart_listView;
	CartAdapter cartAdapter;
	LinearLayout layout;
	List<Cartbean> list=new ArrayList<Cartbean>();
	private boolean flag = true;// 全选或取消全选

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cart);
		initView();
		initViews();
		initData();
	}

	

	private void initView() {

		cart_all_check = (CheckBox) findViewById(R.id.cart_all_check);
		cartTotalPrice = (TextView) findViewById(R.id.cartTotalPrice);
		delete_goods = (TextView) findViewById(R.id.delete_goods);
		checkOut = (TextView) findViewById(R.id.checkOut);
		cart_listView = (ListView) findViewById(R.id.cart_listView);
		layout = (LinearLayout) findViewById(R.id.price_relative);
		ClickListener cl = new ClickListener();
		cart_all_check.setOnClickListener(cl);
		delete_goods.setOnClickListener(cl);
		checkOut.setOnClickListener(cl);

	}
	private void initViews() {
		list = new ArrayList<Cartbean>();
		
		//list=MyApplication.list;
	cartAdapter=new CartAdapter(handler, getApplication(), R.layout.activity_cart_item, list);
		cart_listView.setAdapter(cartAdapter);
	}
	
	private void initData() {
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("flag", "17");
		params.addBodyParameter("u_id", "1");
		Log.e("url", url);
		utils.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				Log.e("nide", "失败");
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				Gson gson = new Gson();
				Type typeOfT = new TypeToken<List<Cartbean>>() {
				}.getType();
			List<Cartbean> resultList = gson.fromJson(result, typeOfT);
			list.addAll(resultList);
				Log.e("lulu", list.toString());
				cartAdapter.notifyDataSetChanged();
			}
		});

	}

	private final class ClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.cart_all_check:// 全选
				selectAll();

				break;
			case R.id.delete_goods:// 删除
				String shopIndex = deleteOrCheckOutcart();
				showDialogDelete(shopIndex);
				break;
			case R.id.checkOut:// 结算
				goCheckOut();
				break;
			default:
				break;
			}

		}
	}

	private void goCheckOut() {
		// 结算
		String cartIndex = deleteOrCheckOutcart();
		Intent intent = new Intent(CartActivity.this, CheckoutActivity.class);
		intent.putExtra("shopIndex", cartIndex);
		startActivity(intent);
	}
	private void selectAll() {
		// 全选或者全取消
		for (int i = 0; i < list.size(); i++) {
			CartAdapter.getIsSelected().put(i, flag);
		}
		cartAdapter.notifyDataSetChanged();

	}
	private String deleteOrCheckOutcart() {
		// 删除或结算商品
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			if (CartAdapter.getIsSelected().get(i)) {
				stringBuffer.append(i);
				stringBuffer.append(",");
			}

		}
		stringBuffer.deleteCharAt(stringBuffer.length() - 1);
		return stringBuffer.toString();
	}

	private void showDialogDelete(String shopIndex) {

		// 弹出对话框询问用户是否删除被选中的商品
		final String[] delShopIndex = shopIndex.split(",");
		new AlertDialog.Builder(CartActivity.this)
				.setMessage("您确定删除这" + delShopIndex.length + "商品吗？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						for (String string : delShopIndex) {
							int index = Integer.valueOf(string);
							list.remove(index);
							// listcb.remove(index);
							// list.get(index).getP_id();
						}
						flag = false;
						selectAll(); // 删除商品后，取消所有的选择
						flag = true; // 刷新页面后，设置Flag为true，恢复全选功能

					}
				}).setNegativeButton("取消", null).create().show();

	}



	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 10) { // 更改选中商品的总价格
				float price = (Float) msg.obj;
				if (price > 0) {
					cartTotalPrice.setText("￥" + price);
					layout.setVisibility(View.VISIBLE);
				} else {
					layout.setVisibility(View.GONE);
				}
			} else if (msg.what == 11) {
				// 所有列表中的商品全部被选中，让全选按钮也被选中
				// flag记录是否全被选中
				flag = !(Boolean) msg.obj;
				cart_all_check.setChecked((Boolean) msg.obj);
			}
		}
	};

}
